//
//  ZJStatues.swift
//  Webo
//
//  Created by 曾静 on 16/6/27.
//  Copyright © 2016年 qq. All rights reserved.
//

import UIKit

class ZJStatues: NSObject {

    
    //  发微博事件
    var created_at: String?
    
    //时间的计算型属性
    var creatString:String?{
        
        return getWebTimeWithStr(created_at ?? "")
    }
    //  微博ID,记得采用int64位的
    var id: Int64 = 0
    //  微博内容
    var text: String?
    //  微博来源
    var source: String?{
        
        didSet{
          sourceAttr = getAttrString(source)
        }
    }
    //  用户模型
    var user: ZJUsers?
    
    //	int	转发数
    var reposts: String?
    //	int	评论数
    var comments: String?
    //	int	表态数
    var attitudes: String?
    
    //添加转发微博的属性
    var retweeted_status:ZJStatues?
    
    //  微博来源
    var sourceAttr: NSMutableAttributedString?
    
    

    //图片的数组
    var pic_urls:[ZJPicture]?{
        
        didSet{
            
           picSize = getItemSize(pic_urls?.count ?? 0)
            
        }
    }
    
    
    
    //图片视图的尺寸信息
    var picSize:CGSize?
    
    func getItemSize(count:Int)->CGSize{
        
        // cell 之间的间距
         let itemMargin: CGFloat = 5
        
        let  itemWH = (SCREENW - 2 * itemMargin - 2 * OriginalMargin)/3
        
        let col = count == 4 ? 2 : (count >= 3 ? 3 : count)
        
        let row = count == 4 ? 2 : ((count - 1)/3 + 1)
        
        //计算配图的高度
        return CGSizeMake(itemWH * CGFloat(col) + CGFloat((col - 1)) * itemMargin, itemWH * CGFloat(row) + CGFloat((row - 1)) * itemMargin)
        
    }
    //更改为存储属性
    var reposts_count:Int = 0{
        didSet{
            
            reposts = getCount(reposts_count, title: "转发")
        }
    }
    //	int	评论数
    var comments_count:Int = 0{
        didSet{
            
            comments = getCount(comments_count, title: "评论")
        }
    }
    //	int	表态数
    var attitudes_count:Int = 0{
        didSet{
            
            attitudes = getCount(attitudes_count, title: "赞")
           
        }
    }
    
    //传进一个soure给出一个已经创建好的富文本
    func getAttrString(soure:String?) ->NSMutableAttributedString{
        
        //判断来源是否存在
       guard let s = soure where s.containsString("\">") else{
           return self.makeStringBecomeAttrString("来自 哪颗星")
        }
        
        
        let str = s.substringWithRange(s.rangeOfString("\">")!.endIndex..<s.rangeOfString("</a")!.startIndex)
        
        return self.makeStringBecomeAttrString("来自 \(str)")
        
        
    }
    
    func getWebTimeWithStr(creatTime:String)->String{
        
        //以下步骤的作用是将传进来的字符串的时间转化为微博时间
        
        let df = NSDateFormatter()
        
        df.locale = NSLocale(localeIdentifier: "en_US")
        
        //Thu Jun 30 11:21:04 +0800 2016
        df.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        
        //将字符串转化为date
        let wbDate = df.dateFromString(creatTime)!
        
        if isThisYear(wbDate){
            //是今年
            let calender = NSCalendar.currentCalendar()
            
            if calender.isDateInToday(wbDate) {
                
            let s = NSDate().timeIntervalSinceDate(wbDate)
                
                if s < 60{
                    return "刚刚"
                }else if s >= 60 && s < 60*60 {
                    
                    return  "\(Int(s/60))分钟前"
                    
                }else{
                    
                    return "\(Int(s/3600))小时前"
                }
                
                
            }else if calender.isDateInYesterday(wbDate){
                   // 昨天 显示格式: 昨天 12:12
                df.dateFormat = "昨天 HH:mm"
                
                return df.stringFromDate(wbDate)
                
            }else{
                // 其他 显示格式: 06月12日 13:13
                df.dateFormat = "MM月dd日 HH:mm"
                
                 return df.stringFromDate(wbDate)
            }
            
            
        }else{
            //不是今年
            // 代表不是今年 显示格式: 2015年05月05日 10:10
            df.dateFormat = "yyyy年MM月dd日 HH:mm"
            
            return df.stringFromDate(wbDate)
            
        }
        
        
        
        
    }
    
    
    //判断是不是今年
    func isThisYear(date:NSDate)->Bool{
        
        let df = NSDateFormatter()
    
        df.locale = NSLocale(localeIdentifier: "en_US")
        
        df.dateFormat = "yyyy"
        
        //将date转化为字符串
        let currentYear = df.stringFromDate(NSDate())
        
        let WebYear = df.stringFromDate(date)
        
        if WebYear == currentYear {
            
            return true
            
        }else{
            
            return false
            
        }
        
        
        
    }
    //通过传进一个字符串,返回特定格式
    func makeStringBecomeAttrString(str:String)->NSMutableAttributedString{
        //将传进来的字符串转化为副文本
        let attr = NSMutableAttributedString(string: str)
        //将传进来的字符串转化为oc的字符串,并且遍历字符串.找到"来自"的位置(范围)
        let range = (str as NSString).rangeOfString("来自")
        //将计算的range传进更改富文本属性的方法里面
        attr.addAttributes([NSForegroundColorAttributeName : UIColor.orangeColor()], range: range)
        return attr
        
    }
    
    func getCount(count:Int,title:String) ->String{
        
        
        
        if  count <= 0{
            
            return title
            
        }else if count > 0 && count < 10000 {
            
            return "\(count)"
            
        }else{
            
            var num:String = "\(CGFloat(count/1000)/10)"
            
            if  num.containsString(".0") {
              num = num.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            
            return "\(num)万"
        }
    }
    
    
    //只读属性消耗cup,由于每次滚动cell都要加载数据,每次都要获取值,所以我们改变成为存储型
    
    init(dict:[String:AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }
    
    //在kvc赋值的时候判断key是不是user,之后字典转模型
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            
            guard let v = value as? [String:AnyObject] else{
                
                return
            }
            
            user = ZJUsers(dict: v)
            
        }else if key == "retweeted_status"{
            
            guard let v = value as? [String:AnyObject] else{
                
                return
            }
            
            retweeted_status = ZJStatues(dict: v)
            
        }else if key == "pic_urls"{
            
            guard let v = value as?[[String:AnyObject]] else{
                return
            }
            
            var marr:[ZJPicture] = [ZJPicture]()
            
            for dic in v{
                
                let pic = ZJPicture(dict: dic)
                
                marr.append(pic)
            }
            
            pic_urls = marr
            
        }else{
            
            super.setValue(value, forKey: key)
        }
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    override var description: String{
        
        let keys = ["created_at", "id", "text", "source", "user"]
        
        return dictionaryWithValuesForKeys(keys).description
    }

    
    
    
}
